package com.yyfax.ph.home.recommendloan.otherinfo;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.common.form.FormRow;
import com.yyfax.common.tools.SoftKeyboardUtils;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseFragment;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.widgets.pickerview.view.OptionsPickerView;
import com.yyfax.ph.home.datainit.OptionsModel;
import com.yyfax.ph.home.datainit.OptionsPresenter;
import com.yyfax.ph.home.recommendloan.RecommendLoanSuccessActivity;

import java.util.ArrayList;

/**
 * 提交补充资料
 * Created by ying_he on 2017/11/4.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class OtherInfoFragment extends BaseFragment implements OptionsPresenter.View, OtherInfoPresenter.View {
	private static final String TAG = OtherInfoFragment.class.getSimpleName();

	private static final int LOADER_ID_OPTIONS = 1001;
	private static final int LOADER_ID_UPLOAD_OTHER_INFO = 1002;
	private static final String BUNDLE_KEY_RCM_ID = "bundle_key_rcm_id";

	private static final String BUNDLE_KEY_HAS_NATIVE_HOUSE = "bundle_key_has_native_house";
	private static final String BUNDLE_KEY_LIVING_CONDITION = "bundle_key_living_condition";
	private static final String BUNDLE_KEY_MARRIAGE_CONDITION = "bundle_key_marriage_condition";
	private static final String BUNDLE_KEY_EDUCATION_DEGREE = "bundle_key_education_degree";
	private static final String BUNDLE_KEY_WORK_TYPE = "bundle_key_work_type";
	private static final String BUNDLE_KEY_COMPANY_NAME = "bundle_key_company_name";

	@BindView(R.id.credit_switch)
	Switch mCreditSwitch;
	@BindView(R.id.living_condition)
	FormRow mLivingConditionFR;
	@BindView(R.id.marrage_status)
	FormRow mMarriageStatusFR;
	@BindView(R.id.education_degree)
	FormRow mEducationDegreeFR;
	@BindView(R.id.office_worker_rb)
	RadioButton mOfficeWorkerRb;
	@BindView(R.id.business_owner_rb)
	RadioButton mBusinessOwnerRb;
	@BindView(R.id.work_kind_group)
	RadioGroup mWorkKindGroup;
	@BindView(R.id.work_kind_ll)
	LinearLayout mWorkKindLl;
	@BindView(R.id.company_name_fr)
	FormRow mCompanyNameFr;
	@BindView(R.id.btn_recommend)
	Button mBtnRecommend;

	Unbinder mUnBinder;
	private OptionsPresenter mOptionsPresenter;
	private OtherInfoPresenter mOtherInfoPresenter;
	private String mRcmId = "";

	// 婚姻状况
	private OptionsPickerView mMarriagePicker;
	private OptionsModel.OptionBean mSelectedMarriage;
	private ArrayList<OptionsModel.OptionBean> mMarriageList = new ArrayList<>();

	// 教育程度
	private OptionsPickerView mEducationPicker;
	private OptionsModel.OptionBean mSelectedEducation;
	private ArrayList<OptionsModel.OptionBean> mEducationList = new ArrayList<>();

	// 居住状况
	private OptionsPickerView mLivingConditionPicker;
	private OptionsModel.OptionBean mSelectedLivingCondition;
	private ArrayList<OptionsModel.OptionBean> mLivingConditionList = new ArrayList<>();

	public static OtherInfoFragment newInstance(String rcmId) {
		OtherInfoFragment fragment = new OtherInfoFragment();
		Bundle args = new Bundle();
		args.putString(BUNDLE_KEY_RCM_ID, rcmId);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_OPTIONS, null, this);
		getLoaderManager().initLoader(LOADER_ID_UPLOAD_OTHER_INFO, null, this);

	}

	@Override
	public void onDetach() {
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID_OPTIONS);
		getLoaderManager().destroyLoader(LOADER_ID_UPLOAD_OTHER_INFO);

	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_supply_info, null);
		mUnBinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (savedInstanceState != null){
			readBundle(savedInstanceState);
		}else {
			mRcmId = getArguments().getString(BUNDLE_KEY_RCM_ID);
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_OPTIONS:
				return new PresenterLoader<>(getActivity(), new OptionsPresenter.Generator());
			case LOADER_ID_UPLOAD_OTHER_INFO:
				return new PresenterLoader<>(getActivity(), new OtherInfoPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_OPTIONS:
				mOptionsPresenter = (OptionsPresenter) data;
				mOptionsPresenter.attach(this);
				String type = Constants.OPTION_EDUCATION_LEVEL + "," + Constants.OPTION_LIVING_CONDITION + "," + Constants.OPTION_MARRIAGE;
				mOptionsPresenter.getOptions(type);
				break;
			case LOADER_ID_UPLOAD_OTHER_INFO:
				mOtherInfoPresenter = (OtherInfoPresenter) data;
				mOtherInfoPresenter.attach(this);
				break;
			default:
				break;
		}
	}

	@OnClick({R.id.marrage_status, R.id.education_degree, R.id.living_condition, R.id.btn_recommend})
	public void onClicked(View view) {
		switch (view.getId()) {
			case R.id.living_condition:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				showLivingConditionOptions();
				break;
			case R.id.marrage_status:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				showMarriageOptions();
				break;
			case R.id.education_degree:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				showEducationOptions();
				break;
			case R.id.btn_recommend:
				submitOtherInfo();
				break;
			default:
				break;
		}

	}

	/**
	 * 选择居住状况
	 */
	public void showLivingConditionOptions() {
		if (null != mLivingConditionPicker) {
			mLivingConditionPicker.show();
		} else {
			showToast(R.string.get_data_failed);
		}
	}

	/**
	 * 选择婚姻状况
	 */
	private void showMarriageOptions() {
		if (null != mMarriagePicker) {
			mMarriagePicker.show();
		} else {
			showToast(R.string.get_data_failed);
		}
	}

	/**
	 * 选择教育状况
	 */
	private void showEducationOptions() {
		if (null != mEducationPicker) {
			mEducationPicker.show();
		} else {
			showToast(R.string.get_data_failed);
		}
	}

	public void submitOtherInfo() {
		if (!mLivingConditionFR.validate()) { // 居住状况
			return;
		}
		if (!mMarriageStatusFR.validate()) { // 婚姻
			return;
		}
		if (!mEducationDegreeFR.validate()) { // 教育
			return;
		}

		if (!mCompanyNameFr.validate()) { // 单位名称
			return;
		}

		OtherInfoModel.OtherInfoParams otherInfoParams = new OtherInfoModel.OtherInfoParams();
		otherInfoParams.rcmdId = mRcmId;
		otherInfoParams.employeeType = mOfficeWorkerRb.isChecked() ? Constants.WORK_TYPE_OFFICE_WORKER : Constants.WORK_TYPE_BUSINESS_OWNER;
		otherInfoParams.corpName = mCompanyNameFr.getText();
		otherInfoParams.localHouseFlag = mCreditSwitch.isChecked() ? Constants.HAS_NATIVE_HOUSE : Constants.NO_NATIVE_HOUSE;
		otherInfoParams.livingCondition = mSelectedLivingCondition.getValue();
		otherInfoParams.marriage = mSelectedMarriage.getValue();
		otherInfoParams.educationLevel = mSelectedEducation.getValue();

		mOtherInfoPresenter.uploadOtherInfo(otherInfoParams);
	}

	@Override
	public void onGetOptions(OptionsModel.OptionsBean options) {
		initMarriageOption(options);
		initEducationOption(options);
		initLivingConditionOption(options);
	}

	public void initMarriageOption(OptionsModel.OptionsBean options) {
		if (null != options && options.marriage_type != null && options.marriage_type.size() > 0) {
			if (mMarriageList.size() > 0) {
				mMarriageList.clear();
			}
			mMarriageList.addAll(options.marriage_type);
			mMarriagePicker = new OptionsPickerView(getActivity());
			mMarriagePicker.setPicker(mMarriageList);
			mMarriagePicker.setTitle(getString(R.string.picker_title_select_marriage_condition));
			mMarriagePicker.setCyclic(false, false, false);
			mMarriagePicker.setSelectOptions(1, 0, 0);
			mMarriagePicker.setOnoptionsSelectListener(new OptionsPickerView
					.OnOptionsSelectListener() {

				@Override
				public void onOptionsSelect(int options1, int option2,
						int options3) {
					mSelectedMarriage = mMarriageList.get(options1);
					String tx = mSelectedMarriage.getPickerViewText();
					mMarriageStatusFR.setText(tx);
				}
			});
		}
	}

	public void initEducationOption(OptionsModel.OptionsBean options) {
		if (null != options && options.education_type != null && options.education_type.size() > 0) {
			if (mEducationList.size() > 0) {
				mEducationList.clear();
			}
			mEducationList.addAll(options.education_type);
			mEducationPicker = new OptionsPickerView(getActivity());
			mEducationPicker.setPicker(mEducationList);
			mEducationPicker.setTitle(getString(R.string.picker_title_select_education_condition));
			mEducationPicker.setCyclic(false, false, false);
			mEducationPicker.setSelectOptions(2, 0, 0);
			mEducationPicker.setOnoptionsSelectListener(new OptionsPickerView
					.OnOptionsSelectListener() {

				@Override
				public void onOptionsSelect(int options1, int option2,
						int options3) {
					mSelectedEducation = mEducationList.get(options1);
					String tx = mSelectedEducation.getPickerViewText();
					mEducationDegreeFR.setText(tx);
				}
			});
		}
	}

	public void initLivingConditionOption(OptionsModel.OptionsBean options) {
		if (null != options && options.living_type != null && options.living_type.size() > 0) {
			if (mLivingConditionList.size() > 0) {
				mLivingConditionList.clear();
			}
			mLivingConditionList.addAll(options.living_type);
			mLivingConditionPicker = new OptionsPickerView(getActivity());
			mLivingConditionPicker.setPicker(mLivingConditionList);
			mLivingConditionPicker.setTitle(getString(R.string.picker_title_select_living_condition));
			mLivingConditionPicker.setCyclic(false, false, false);
			mLivingConditionPicker.setSelectOptions(2, 0, 0);
			mLivingConditionPicker.setOnoptionsSelectListener(new OptionsPickerView
					.OnOptionsSelectListener() {

				@Override
				public void onOptionsSelect(int options1, int option2,
						int options3) {
					mSelectedLivingCondition = mLivingConditionList.get(options1);
					String tx = mSelectedLivingCondition.getPickerViewText();
					mLivingConditionFR.setText(tx);
				}
			});

		}
	}

	@Override
	public void uploadOtherInfoSuccess(String msg) {
		// 跳转推荐成功
		RecommendLoanSuccessActivity.start(getActivity());
		getActivity().finish();
	}

	@Override
	public void uploadOtherInfoFailed(String msg) {
		showToast(msg);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnBinder.unbind();
	}

	private void readBundle(Bundle bundle){
		mRcmId = bundle.getString(BUNDLE_KEY_RCM_ID);
		mCreditSwitch.setChecked(bundle.getBoolean(BUNDLE_KEY_HAS_NATIVE_HOUSE, false));
		mSelectedLivingCondition = bundle.getParcelable(BUNDLE_KEY_LIVING_CONDITION);
		if (mSelectedLivingCondition != null) {
			mLivingConditionFR.setText(mSelectedLivingCondition.getPickerViewText());
		}

		mSelectedMarriage = bundle.getParcelable(BUNDLE_KEY_MARRIAGE_CONDITION);
		if (mSelectedMarriage != null) {
			mMarriageStatusFR.setText(mSelectedMarriage.getPickerViewText());
		}

		mSelectedEducation = bundle.getParcelable(BUNDLE_KEY_EDUCATION_DEGREE);
		if (mSelectedEducation != null) {
			mEducationDegreeFR.setText(mSelectedEducation.getPickerViewText());
		}

		boolean isOfficeWorkerRbChecked = bundle.getBoolean(BUNDLE_KEY_WORK_TYPE, true);
		if (isOfficeWorkerRbChecked){
			mOfficeWorkerRb.setChecked(true);
			mBusinessOwnerRb.setChecked(false);
		}else {
			mOfficeWorkerRb.setChecked(false);
			mBusinessOwnerRb.setChecked(true);
		}
		mCompanyNameFr.setText(bundle.getString(BUNDLE_KEY_COMPANY_NAME, ""));
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(BUNDLE_KEY_RCM_ID, mRcmId);
		outState.putBoolean(BUNDLE_KEY_HAS_NATIVE_HOUSE, mCreditSwitch.isChecked());
		outState.putParcelable(BUNDLE_KEY_LIVING_CONDITION, mSelectedLivingCondition);
		outState.putParcelable(BUNDLE_KEY_MARRIAGE_CONDITION, mSelectedMarriage);
		outState.putParcelable(BUNDLE_KEY_EDUCATION_DEGREE, mSelectedEducation);
		outState.putBoolean(BUNDLE_KEY_WORK_TYPE, mOfficeWorkerRb.isChecked());
		outState.putString(BUNDLE_KEY_COMPANY_NAME, mCompanyNameFr.getText());
	}
}
